<template>
  <div class="course-review">
    <div class="page-header">
      <h2>选课审核</h2>
      <p class="page-desc">审核学生的选修课申请</p>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true">
        <el-form-item label="学期">
          <el-select v-model="filterForm.semester" placeholder="请选择学期" style="width: 200px" @change="fetchApplications">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="fetchApplications">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card pending">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ pendingCount }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card approved">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ approvedCount }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card rejected">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ rejectedCount }}</div>
              <div class="stat-label">已拒绝</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待审核申请列表 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>待审核申请</span>
          <el-button type="success" size="small" @click="batchApprove" :disabled="selectedRows.length === 0">
            <el-icon><Check /></el-icon>
            批量通过 ({{ selectedRows.length }})
          </el-button>
        </div>
      </template>

      <el-table
        :data="applications"
        v-loading="loading"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="studentName" label="姓名" width="100" />
        <el-table-column prop="studentSex" label="性别" width="60" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.studentSex === 1 ? 'primary' : 'danger'" size="small">
              {{ scope.row.studentSex === 1 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="clazzName" label="班级" width="150" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="courseType" label="课程类型" width="100" align="center">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.courseType }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="credit" label="学分" width="70" align="center" />
        <el-table-column prop="selectTime" label="申请时间" width="160" />
        <el-table-column prop="studentPhone" label="联系电话" width="130" />
        
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleApprove(scope.row)">
              <el-icon><Check /></el-icon>
              通过
            </el-button>
            <el-button type="danger" size="small" @click="handleReject(scope.row)">
              <el-icon><Close /></el-icon>
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 拒绝原因对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝选课申请"
      width="500px"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="学生">
          <el-input :value="currentApplication.studentName + ' (' + currentApplication.studentNo + ')'" disabled />
        </el-form-item>
        <el-form-item label="课程">
          <el-input :value="currentApplication.courseName" disabled />
        </el-form-item>
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因，将通知给学生"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmReject">确认拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Clock, CircleCheck, CircleClose, Check, Close } from '@element-plus/icons-vue'
import { getPendingCourseApplications, reviewCourseApplication } from '../api/teacherUser'

// 筛选表单
const filterForm = ref({
  semester: '2024春季'
})

// 数据列表
const applications = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 拒绝对话框
const rejectDialogVisible = ref(false)
const currentApplication = ref({})
const rejectForm = ref({
  reason: ''
})

// 统计数据
const pendingCount = computed(() => applications.value.length)
const approvedCount = ref(0)
const rejectedCount = ref(0)

// 获取待审核申请列表
const fetchApplications = async () => {
  loading.value = true
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.teId
    
    if (!teacherId) {
      ElMessage.error('请先登录')
      return
    }

    console.log('🔍 正在获取待审核申请:', { teacherId, semester: filterForm.value.semester })
    
    const response = await getPendingCourseApplications(teacherId, filterForm.value.semester)
    
    if (response && response.data) {
      applications.value = response.data
      console.log('✅ 获取到待审核申请:', applications.value.length, '条')
      
      if (applications.value.length === 0) {
        ElMessage.info('当前没有待审核的选课申请')
      }
    } else {
      applications.value = []
      ElMessage.warning('未找到待审核申请')
    }
  } catch (error) {
    console.error('❌ 获取待审核申请失败:', error)
    ElMessage.error('获取待审核申请失败: ' + (error.message || ''))
    applications.value = []
  } finally {
    loading.value = false
  }
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 通过申请
const handleApprove = async (application) => {
  try {
    await ElMessageBox.confirm(
      `确定通过 ${application.studentName} 的选课申请吗？`,
      '确认通过',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    console.log('✅ 通过申请:', application.studentCourseId)
    
    const result = await reviewCourseApplication(application.studentCourseId, true, null)
    
    if (result && result.code === 200) {
      ElMessage.success('已通过该学生的选课申请')
      await fetchApplications()  // 刷新列表
      approvedCount.value++
    } else {
      ElMessage.error('审核失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('❌ 审核失败:', error)
      ElMessage.error('审核失败: ' + (error.message || ''))
    }
  }
}

// 拒绝申请
const handleReject = (application) => {
  currentApplication.value = application
  rejectForm.value.reason = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason || rejectForm.value.reason.trim() === '') {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  try {
    console.log('❌ 拒绝申请:', currentApplication.value.studentCourseId, '原因:', rejectForm.value.reason)
    
    const result = await reviewCourseApplication(
      currentApplication.value.studentCourseId,
      false,
      rejectForm.value.reason
    )
    
    if (result && result.code === 200) {
      ElMessage.success('已拒绝该学生的选课申请')
      rejectDialogVisible.value = false
      await fetchApplications()  // 刷新列表
      rejectedCount.value++
    } else {
      ElMessage.error('审核失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 审核失败:', error)
    ElMessage.error('审核失败: ' + (error.message || ''))
  }
}

// 批量通过
const batchApprove = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要通过的申请')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定批量通过 ${selectedRows.value.length} 条选课申请吗？`,
      '批量通过',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    let successCount = 0
    let failCount = 0
    
    for (const application of selectedRows.value) {
      try {
        const result = await reviewCourseApplication(application.studentCourseId, true, null)
        if (result && result.code === 200) {
          successCount++
        } else {
          failCount++
        }
      } catch (error) {
        failCount++
        console.error('审核失败:', application.studentName, error)
      }
    }
    
    ElMessage.success(`批量审核完成：成功 ${successCount} 条，失败 ${failCount} 条`)
    approvedCount.value += successCount
    await fetchApplications()  // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('❌ 批量审核失败:', error)
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.course-review {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.page-desc {
  color: #6c757d;
  font-size: 14px;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
}

.stat-card.pending .stat-icon {
  background: #fff3e0;
  color: #ff9800;
}

.stat-card.approved .stat-icon {
  background: #e8f5e9;
  color: #4caf50;
}

.stat-card.rejected .stat-icon {
  background: #ffebee;
  color: #f44336;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

.table-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background: #f5f7fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}
</style>

